package com.db.mongodb;

import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.spider.util.SpiderCondition;
import com.spider.util.SpiderProperties;

public class MongoDBUtil {

	public static final String MONGODB_IP = String.valueOf(SpiderProperties.getString(SpiderCondition.MONGODB_IP));
	public static final Integer MONGODB_PORT = Integer.parseInt(SpiderProperties.getString(SpiderCondition.MONGODB_PORT, "27017"));
	public static final String MONGODB_DB = String.valueOf(SpiderProperties.getString(SpiderCondition.MONGODB_DB));
	private static final Logger log = Logger.getLogger(MongoDBUtil.class);

	private static Map<String, Mongo> mongoInstances = new ConcurrentHashMap<String, Mongo>();
	private static Map<String, DB> mongoDBInstances = new ConcurrentHashMap<String, DB>();

	public static DB mongoDB = null;
	
	static {
		try {
			mongoDB = getInstance(MONGODB_IP, MONGODB_PORT, MONGODB_DB);
		} catch (Exception e) {
			log.error("get mongodb connection error....");
		}
	}

	private static DB getInstance(String ip, int prot, String dbName) throws UnknownHostException, MongoException {
			String mongokey = prot + "" + ip;
			String mongodbkey = mongokey + dbName;
			DB db = null;
			db = mongoDBInstances.get(mongodbkey);
			if (null == db) {
				Mongo m = mongoInstances.get(mongokey);
				if (null == m) {
					m = new Mongo(ip, prot);
					//mongodb pool size
					int poolSize = Integer.parseInt(SpiderProperties.getString(SpiderCondition.MONGODB_POOL_SIZE, "100"));
					m.getMongoOptions().connectionsPerHost = poolSize;
					mongoInstances.put(mongokey, m);
				}
				db = m.getDB(dbName);
				mongoDBInstances.put(mongodbkey, db);
			}
			return db;
		}
}
